package com.panghl.controller;

import com.panghl.utils.RedisUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author panghl
 * @Date 2022/2/23
 **/
@RestController
public class GoodsController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${server.port}")
    private String serverPort;
    // 我等着觉得时间太长了，我想放弃等待。
    // 给我一个规定的时间内，拿不到锁我再放弃
    //if (lock.tryLock()){
    //if (lock.tryLock(3, TimeUnit.SECONDS)){
    //    lock.lock();
    //    lock.unlock();
    //}
    private final Lock lock = new ReentrantLock();

    public static final String REDIS_LOCK = "redis_goods_panghl";

    @Autowired
    private Redisson redisson;

    @GetMapping("/buy_goods")
    public String buy_goods() throws Exception {
        RLock redissonLock = redisson.getLock(REDIS_LOCK);
        redissonLock.lock();
        try {
            String result = redisTemplate.opsForValue().get("goods:001");
            int goodNumber = result == null ? 0 : Integer.parseInt(result);
            if (goodNumber > 0) {
                int realNumber = goodNumber - 1;
                redisTemplate.opsForValue().set("goods:001", String.valueOf(realNumber));
                System.out.println("成功买到商品，库存还剩下" + realNumber + "件" + "\t服务提供者:" + serverPort);
                return "成功买到商品，库存还剩下" + realNumber + "件" + "\t服务提供者:" + serverPort;
            } else {
                return "商品已经售完-->活动结束/调用超时，欢迎下次光临；" + "\t服务提供者:" + serverPort;
            }
        } finally {
            if (redissonLock.isLocked()) {
                if (redissonLock.isHeldByCurrentThread()) {
                    redissonLock.unlock();
                }
            }
        }
    }


}
